package logic

import (
	"context"
	"fmt"
	"math/rand"
	"novel/model/cache"
	"novel/model/mysql"
	"strconv"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *novelrpc.LoginRequest) (*novelrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	Sms, _ := cache.Rdb.Get(l.ctx, "SendsKey"+in.Account).Int64()
	if Sms != in.SendSms {
		return nil, fmt.Errorf("验证码不正确,请稍后再试")
	}

	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		user = mysql.User{
			Account:  in.Account,
			Password: in.Password,
			Image:    "http://t05ktvrux.hn-bkt.clouddn.com/5.png",
			NickName: fmt.Sprintf("游客_%d", rand.Intn(99999)),
		}
		mysql.DB.Create(&user)
	} else {
		if in.Password != user.Password {
			return nil, fmt.Errorf("密码不正确,请重试")
		}
	}

	return &novelrpc.LoginResponse{
		UserId: strconv.Itoa(int(user.ID)),
	}, nil
}
